import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios';
import { promptAction } from '@kit.ArkUI';
import { AnyObject } from '../../models/HttpModel';


const request = axios.create({
    // baseURL: 'http://192.168.111.144:6060'
    // baseURL: 'http://localhost:6060'
    baseURL: 'http://192.168.31.105:6060'
})

// 添加请求拦截器
request.interceptors.request.use((config: InternalAxiosRequestConfig) => {
    console.log(JSON.stringify(config), 'config')
    // 对请求数据做点什么
    // config.headers['Content-Type'] = 'application/json'
    // console.log(JSON.stringify(config), 'config')
    return config;
}, (error: AxiosError) => {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
request.interceptors.response.use((response: AxiosResponse) => {

    // 对响应数据做点什么
    if (response.data.code === 200) {
        return response.data.data;
    } else {
        promptAction.showToast({ message: response.data.message })
        return Promise.reject(response.data.message)
    }

}, (error: AxiosError) => {
    // 对响应错误做点什么
    promptAction.showToast({ message: error.message })
    return Promise.reject(error.message);
});

export default class Http {
    get<T>(url: string, params?: AnyObject) {
        return request.get<ESObject, T>(url, {
            params
        })
    }

    post<T>(url: string, data: AnyObject) {
        return request.get<ESObject, T>(url, data)
    }

    put<T>(url: string, data: AnyObject) {
        return request.put<ESObject, T>(url, data)
    }

    delete<T>(url: string, params?: AnyObject) {
        return request.delete<ESObject, T>(url, {
            params
        })
    }
}